import {Context} from "../dep.ts";
import {Kv} from "../db.ts";
const index = (ctx: Context) => {
    ctx.response.body = `<!DOCTYPE html>
    <html>
      <head><title>Hello oak!</title><head>
      <body>
        <h1>Hello oak!</h1>
      </body>
    </html>
  `;
};

const getAllbooks = async (context: Context) => {
    let iter = Kv.list<string>({prefix: ["book"]});
    const books = [];
    for await (const res of iter) books.push(res.value);
    context.response.body = books;
};

const getBookbyId = async (context: Context) => {
    if (context?.params?.id) {
        let iter = Kv.list<string>({prefix: ["book"], start: [context?.params?.id]});
        const books = [];
        for await (const res of iter) books.push(res.value);
        context.response.body = books[0];
    }
};

const testGitlib = async (context: Context) => {
    try {
        const jsonResponse = await fetch("https://api.github.com/users/denoland");
        const jsonData = await jsonResponse.json();
        context.response.body = jsonData;
    } catch (err) {
        context.response.status = 500;
        context.response.body = {msg: err.message};
    }

};

export {index, getAllbooks, testGitlib, getBookbyId};